
import argparse
# -- coding: utf-8 --

import sys
import copy
import ctypes

from ctypes import *
import os
import numpy as np
import cv2
import random


def loginfo(opt, info):
    if opt.log_handle is not None:
        #self.step(i, 10, 'it', None)
        opt.log_handle.stepSignal.emit(info)
        return not opt.log_handle.running
    else:
        #print(info)
        pass

    return False

def listdir(dir, filter=None):
    if not os.path.isdir(dir):
        return []
        
    liall = os.listdir(dir)
    if filter is None:
        return liall

    if isinstance(filter,str):
        li = []
        for x in liall:
            if filter in x:
                li.append(x)

    elif isinstance(filter, list):
        li = []
        for x in liall:
            _,ext = os.path.splitext(x)
            if ext in filter:
                li.append(x)

    li = [f'{dir}/{x}' for x in li]
    return li

def get_classes(train_list):
    names = []
    for fn,bnds in train_list:
        for r,t in bnds:
            names.append(t)
    
    classes = sorted(list(set(names)))
    return classes


def name2index(train_list, classes):
    names = []
    for fn,bnds in train_list:
        for a in bnds:
            if len(a)>1:
                a[1] = classes.index(a[1])
    
    classes = sorted(list(set(names)))
    return classes

def split_train(data, test_ratio=0.1):
    shuffled_indices = data[:]
    random.shuffle(shuffled_indices)
    test_set_size = int(len(data)*test_ratio)
    test_data = shuffled_indices[:test_set_size]
    train_data = shuffled_indices[test_set_size:]
    return train_data, test_data

def get_config(pa, xinghao, imgsz=416, name=''):
# def get_config(pa, imgsz=416, name=''):
    class Config:
        def __init__(self, **args):
            self.__dict__.update(args)
    opt = Config(adam=False, artifact_alias='latest', batch_size=16, bbox_interval=-1, bucket='', cache_images=False, dataloader=None, device='0', entity=None, evolve=False, exist_ok=False, image_weights=False, img_size=[416, 416], imgsz=416, label_smoothing=0.0, linear_lr=False, local_rank=-1, log_handle=None, model=None, multi_scale=False, names=['1'], noautoanchor=False, nosave=False, notest=False, notrain=False, org_pa='./', pa='./', plots=False, project='.//work_pa/yolov5', quad=False, rect=False, resume=False, save_dir='.//work_pa/yolov5', save_images_dir='.//work_pa/yolov5/test/out', save_img=True, save_json=False, save_labels_dir='.//work_pa/yolov5/test/out', save_period=-1, save_txt=False, save_xml=False, single_cls=False, sync_bn=False, task='test', test_pa='.//work_pa/yolov5/test', train_pa='.//work_pa/yolov5/train', upload_dataset=False, work_pa='.//work_pa', workers=0)
    
    opt.hyp='data/hyps/hyp.scratch.yaml'
    mname = 'yolov5s'
    opt.epochs = 3000
    opt.cfg = f'./models/{mname}.yaml'
    opt.log_handle = None
    opt.save_xml=False
    opt.imgsz=imgsz
    opt.img_size = [imgsz,imgsz]
    opt.save_img=False
    opt.save_img=True
    opt.save_json=False
    opt.plots=False
    opt.notrain = False
    # 'SGD', 'Adam', 'AdamW'
    opt.optimizer = 'SGD'
    opt.cos_lr = False
    work_pa = f'{pa}/work_pa'
    opt.data = f'{work_pa}/data.yaml'
    #opt.arg_pa = pa
    name = '_'.join([mname, str(imgsz), name])
    arg_pa = f'{work_pa}/{name}'
    opt.project = f'{arg_pa}'
    opt.save_dir = arg_pa
    opt.model_pa = f'{pa}/models/{name}/{xinghao}'
    # opt.model_pa = f'{pa}/models/{name}'
    opt.best = f'{opt.model_pa}/best.pt'
    opt.last = f'{opt.model_pa}/last.pt'
    #opt.data = check_file(opt.data)  # check file
    opt.work_pa = work_pa
    opt.org_pa = f'{pa}'
    opt.arg_pa = arg_pa
    opt.train_pa = f"{arg_pa}/train"
    opt.test_pa = f"{arg_pa}/test"
    
    #mkdir(f'{work_pa}/weights')
    #project=f'{opt.work_pa}/test'  # save to project/name
    opt.test_pa = f"{arg_pa}/test"

    opt.model = None
    opt.dataloader = None
    #opt.save_json |= opt.data.endswith('coco.yaml')
    opt.save_json = False
    opt.save_txt = False
    #opt.save_img = False
    opt.save_img = True

    #project=f'{opt.work_pa}/test'  # save to project/name
    testpa = f'{arg_pa}/test'  # increment run

    opt.save_labels_dir = f'{testpa}/out'
    opt.save_images_dir = f'{testpa}/out'

    # Data
    #opt.data = {}
    #opt.data['test'] = testpa
    opt.task = 'test'
    fn = f"{opt.arg_pa}/classes.txt"
    if os.path.exists(fn):
        opt.names = [s.strip() for s in open(fn, 'r').readlines()]
    else:
        opt.names = ['1']
    
    #opt.data['nc'] = len(opt.names)
    #opt.data['names'] = opt.names
    #opt.cfg = './models/v5lite-s.yaml'
    return opt

